package net.oschina.ivansong.maven.plugin;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
/**
 * handle script resource such as css,js
 * 
 * @author Administrator
 *
 */
@Mojo(name = "script", defaultPhase = LifecyclePhase.PACKAGE)
public class ScriptMojo extends AbstractMojo {

	@Parameter
	private String targetDir;

	@Parameter
	private String outputDir;
	
	@Parameter
	private String assetVersionFile;

	@Override
	public void execute() throws MojoExecutionException, MojoFailureException {
		getLog().info("-----------handle script ------------------------ ");
		if (targetDir == null || targetDir.trim().length() == 0) {
			targetDir = "src\\main\\webapp\\assets";
		}
		
		if (outputDir == null || outputDir.trim().length() == 0) {
			outputDir = "target\\webapp\\assets";
		}
		
		if (assetVersionFile == null || assetVersionFile.trim().length() == 0) {
			assetVersionFile = "target\\webapp\\asset.version";
		}
		
		getLog().info("-----------target dict:" + targetDir + "  output:" + outputDir + "------------------------ ");
		

		long time = System.currentTimeMillis();
		
		try {
			File targetDirFile = new File(targetDir);
			
			if (!targetDirFile.exists()) {
				return;
			}
			
			String outPutDir = outputDir + time;
			
			File outputDir = new File(outPutDir);
			if (!outputDir.exists()) {
				outputDir.mkdirs();
			}
			
			copyFiles(targetDirFile, targetDir, outPutDir);
			
			File assetFile = new File(assetVersionFile);
			
			if (!assetFile.exists()) {
				assetFile.createNewFile();
			}
			
			FileOutputStream outVersion = new FileOutputStream(assetFile);
			String content =  "asset.version=" + time;
			
			outVersion.write(content.getBytes());
			outVersion.close();
			
		} catch (Exception e) {
			getLog().error(e);
		}

	}
	
	private void copyFiles(File file, String target, String output) throws Exception {
		if (file.isFile()) {
			  FileInputStream in=new FileInputStream(file);
			  String fileName = file.getPath().replace(target, output);
			  File newFile = new File(fileName);
			  
			  if (!newFile.exists()) {
				  newFile.createNewFile();
			  }
			  
			  FileOutputStream out = new FileOutputStream(newFile);
			  byte[] buffer = new byte[2097152];
			  while (true) {
			  	  int ins = in.read(buffer);
			  	  if (ins == -1) {
			  	  	in.close();
			  	  	out.flush();
			  	  	out.close();
			  	  } else {
			  	  	out.write(buffer, 0, ins);
			  	  }
			  }
		} else {
			for (File file2 : file.listFiles()) {
				copyFiles(file2, target, output);
			}
		}
		
	}
	
}
